//
//  MMItemsViewController.m
//  MemeMaker
//
//  Created by Phan Quang Ha on 8/1/13.
//  Copyright (c) 2013 soyo. All rights reserved.
//

#import "MMItemsViewController.h"
#import "MMConstants.h"
#import "MMFile.h"

#import "UITableViewCell+LoadFromNib.h"
#import "MMConstants.h"
#import "MMMainViewController.h"

#import "MMImageView.h"
#import <Social/Social.h>

#import "MMConstants.h"
#import "UIBarButtonItem+Custom.h"

#import "MMAboutViewController.h"

@interface MMItemsViewController ()
{
    NSMutableArray *arrSource;
    NSMutableDictionary *dictSource;
    UIImage *willShareImage;
    NSString *willShareName;
    
}
@end

@implementation MMItemsViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        arrSource = [NSMutableArray array];
        dictSource = [NSMutableDictionary dictionary];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.tblItems.dataSource = self;
    self.tblItems.delegate = self;
    
    self.navigationController.navigationBarHidden = NO;
    
    
    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0")) {
        self.navigationController.navigationBar.barTintColor = TOOLBAR_TINT_COLOR;
        self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
        self.navigationController.navigationBar.translucent = NO;
        
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],UITextAttributeTextColor,nil];
        [self.navigationController.navigationBar setTitleTextAttributes:dic];
        
    }else{
        self.navigationController.navigationBar.tintColor = TOOLBAR_TINT_COLOR;
    }
    
    self.title = APP_NAME;
    
    if (IS_IPHONE_5) {
        [self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"bg-568h.png"]]];
    }else{
        [self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"bg.png"]]];
    }
    
    GADBannerView *adBanner = [[GADBannerView alloc] initWithAdSize:kGADAdSizeBanner];
    adBanner.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    adBanner.rootViewController = self;
    adBanner.adUnitID = ADMOB_PUBLISHER_ID;
    adBanner.delegate = self;
    [self.viewAd addSubview:adBanner];
    [adBanner loadRequest:[GADRequest request]];
}


- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self refresh];
}

- (void) generateTopActions
{
    if (arrSource.count > 0) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeInfoLight];
        [btn addTarget:self action:@selector(didTouchInfoButton:) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *leftBtn = [[UIBarButtonItem alloc] initWithCustomView:btn];
        [self.navigationItem setLeftBarButtonItem:leftBtn];
        
        UIBarButtonItem *rightBtn = [UIBarButtonItem barItemWithImage:[UIImage imageNamed:@"ico_write_new"] size:CGSizeMake(35, 35) target:self action:@selector(createNewMeme:)];
        [self.navigationItem setRightBarButtonItem:rightBtn];
        
        [self.view bringSubviewToFront:_tblItems];
        _tblItems.hidden = NO;
        _viewButtons.hidden = YES;
    }else{
        [self.navigationItem setRightBarButtonItem:nil];
        [self.navigationItem setLeftBarButtonItem:nil];
        [self.view bringSubviewToFront:_viewButtons];
        _viewButtons.hidden = NO;
        _tblItems.hidden = YES;
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)refresh
{
    [self getAllItems];
    [self generateDisplaySource];
    [self.tblItems clearsContextBeforeDrawing];
    [self.tblItems reloadData];
}

- (void)viewDidUnload {
    [self setTblItems:nil];
    [super viewDidUnload];
}
#pragma mark - GetFiles
- (void) getAllItems
{
    [arrSource removeAllObjects];
    NSFileManager *fManager = [NSFileManager defaultManager];
    NSString *workspaceFoler = [DOCUMENT_FOLDER stringByAppendingPathComponent:FOLDER_WORKSPACE];
    
    NSArray *files = [fManager contentsOfDirectoryAtPath:workspaceFoler error:nil];
    NSLog(@"files: %@", files);
    NSArray *extensions = [NSArray arrayWithObjects:@"jpg", @"png", nil];
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"pathExtension IN %@", extensions];
    NSArray *onlyImages = [files filteredArrayUsingPredicate:predicate];
    
    NSMutableArray *arrTemp = [NSMutableArray arrayWithCapacity:onlyImages.count];
    for (NSString *str in onlyImages) {
        MMFile *aFile = [[MMFile alloc] initWithPath:[workspaceFoler stringByAppendingPathComponent:str]];
        [arrTemp addObject:aFile];
    }

    NSArray *arrTempSorted = [arrTemp sortedArrayUsingComparator:^NSComparisonResult(MMFile *obj1, MMFile *obj2) {
        return [obj2.dateModifed compare:obj1.dateModifed];
    }];
    
    [arrSource addObjectsFromArray:arrTempSorted];
    [self generateTopActions];
}
- (void) generateDisplaySource
{
    [dictSource removeAllObjects];
    for (MMFile *file in arrSource) {
        NSDate *key = file.dateModifed;
        NSMutableArray *values = [dictSource objectForKey:key];
        if (!values) {
            values = [NSMutableArray array];
            [dictSource setObject:values forKey:key];
        }
        [values addObject:file];
    }
}
#pragma mark - UITableView
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 140;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return dictSource.count;
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger cellCount;
    NSArray *allKeys = [dictSource allKeys];
    
//    NSArray *sortedKeys = [allKeys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
//        return [obj2 compare:obj1];
//    }];
    
    NSDate *keyForSection = [allKeys objectAtIndex:section];
    
    NSArray *fileInSection = [dictSource objectForKey:keyForSection];
    if (fileInSection.count % 3 == 0) {
        cellCount = fileInSection.count/3;
    }else{
        cellCount = fileInSection.count/3 + 1;
    }
    return cellCount;
}
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MMImagesCell *cell = [tableView dequeueReusableCellWithIdentifier:idImagesCell];
    if (!cell) {
        cell = [UITableViewCell loadCellFromNibName:@"MMImagesCell"];
        cell.delegate = self;
    }
    NSArray *allkeys = [dictSource allKeys];
//    NSArray *keys = [allkeys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
//        return [obj2 compare:obj1];
//    }];
    NSDate *aKey = [allkeys objectAtIndex:indexPath.section];
    NSArray *arr = [dictSource objectForKey:aKey];
    
    if ((indexPath.row * 3 + 0) < arr.count) {
        MMFile *file1 = [arr objectAtIndex:indexPath.row *3 + 0];
        cell.imgView1.image = [UIImage imageWithContentsOfFile:file1.filePath];
        cell.imgView1.name = [[file1.filePath lastPathComponent] stringByDeletingPathExtension];
        cell.imgView1.hidden = NO;
        
        cell.imgView2.image = nil;
        cell.imgView2.name = nil;
        cell.imgView2.hidden = YES;
        cell.imgView3.image = nil;
        cell.imgView3.name = nil;
        cell.imgView3.hidden = YES;
    }
    if ((indexPath.row * 3 + 1) < arr.count) {
        MMFile *file2 = [arr objectAtIndex:indexPath.row *3 + 1];
        cell.imgView2.image = [UIImage imageWithContentsOfFile:file2.filePath];
        cell.imgView2.name = [[file2.filePath lastPathComponent] stringByDeletingPathExtension];
        cell.imgView2.hidden = NO;
        
        cell.imgView3.image = nil;
        cell.imgView3.name = nil;
        cell.imgView3.hidden = YES;
    }
    
    if ((indexPath.row * 3 + 2) < arr.count) {
        MMFile *file3 = [arr objectAtIndex:indexPath.row *3 + 2];
        cell.imgView3.image = [UIImage imageWithContentsOfFile:file3.filePath];
        cell.imgView3.name = [[file3.filePath lastPathComponent] stringByDeletingPathExtension];
        cell.imgView3.hidden = NO;
    }
    return cell;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSArray *allkeys = [dictSource allKeys];
//    NSArray *keys = [allkeys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
//        return [obj2 compare:obj1];
//    }];
    
    NSDate *key = [allkeys objectAtIndex:section];
    
    NSString *formatString = [NSDateFormatter dateFormatFromTemplate:@"ddMMyyyy" options:0
                                                              locale:[NSLocale currentLocale]];
    NSDateFormatter *fm = [[NSDateFormatter alloc] init];
    [fm setDateFormat:formatString];
    NSString *strDate = [fm stringFromDate:key];
    return strDate;
}
- (void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    cell.backgroundColor = TOOLBAR_TINT_COLOR2;
}


- (void) didTouchInfoButton:(UIButton *)btn
{
    MMAboutViewController *aboutController = [[MMAboutViewController alloc] initWithNibName:@"MMAboutViewController" bundle:nil];
    [self.navigationController pushViewController:aboutController animated:YES];
}

- (IBAction)createNewMeme:(UIButton *)sender {
    MMMainViewController *mainController = [[MMMainViewController alloc] initWithNibName:@"MMMainViewController" bundle:nil];
    [self.navigationController pushViewController:mainController animated:YES];
}

- (IBAction)viewAboutScreen:(UIButton *)sender {
    MMAboutViewController *aboutController = [[MMAboutViewController alloc] initWithNibName:@"MMAboutViewController" bundle:nil];
    [self.navigationController pushViewController:aboutController animated:YES];
}

- (IBAction)viewHowToUseScreen:(UIButton *)sender {
}
- (void)didTouchImage:(UIImage *)img withName:(NSString *)name
{
    if (img)
    {
        willShareImage = img;
        willShareName = name;
        
        UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:NSLocalizedString(@"cancel", @"") destructiveButtonTitle:NSLocalizedString(@"delete", @"") otherButtonTitles:NSLocalizedString(@"preview", @""), NSLocalizedString(@"edit", @""), nil];
        
        [sheet showInView:self.view];
    }
    
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex ) {
        case 0:
        {
            [self deleteItem];
        }
            break;
        case 1:
        {
            [self previewItem];
        }
            break;
        case 2:
        {
            [self editPhoto:willShareImage withName:willShareName];
//            [self postToFacebook];
        }
            break;
//        case 3:
//        {
//            [self postToTwitter];
//        }
//            break;
//        case 4:
//        {
//            [self saveToGallery];
//        }
//            break;
        default:
            break;
    }
}

- (void) editPhoto:(UIImage *)img withName:(NSString *)name{
    MMMainViewController *mainController = [[MMMainViewController alloc] initWithNibName:@"MMMainViewController" bundle:nil];
    mainController.needEditImage = YES;
    mainController.willEditImage = img;
    mainController.willEditName = name;
    [self.navigationController pushViewController:mainController animated:YES];
}

- (void) postToFacebook
{
    SLComposeViewController *slShare = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
    [slShare setInitialText:APP_NAME];
    [slShare addImage:willShareImage];
    [self presentViewController:slShare animated:YES completion:nil];
}
- (void) postToTwitter
{
    SLComposeViewController *slShare = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeTwitter];
    [slShare setInitialText:APP_NAME];
    [slShare addImage:willShareImage];
    [self presentViewController:slShare animated:YES completion:nil];
}
- (void) saveToGallery
{
    UIImageWriteToSavedPhotosAlbum(willShareImage, nil, nil, nil);
}
- (void) deleteItem
{
    NSFileManager *fManager = [NSFileManager defaultManager];
    NSString *workspaceFoler = [DOCUMENT_FOLDER stringByAppendingPathComponent:FOLDER_WORKSPACE];
    NSString *willDeletePath = [workspaceFoler stringByAppendingPathComponent:[willShareName stringByAppendingPathExtension:@"png"]];
    
    if ([fManager fileExistsAtPath:willDeletePath]) {
        [fManager removeItemAtPath:willDeletePath error:nil];
    }
    [self refresh];
}
- (void) previewItem
{
    NSString *workspaceFoler = [DOCUMENT_FOLDER stringByAppendingPathComponent:FOLDER_WORKSPACE];
    NSString *willPreviewPath = [workspaceFoler stringByAppendingPathComponent:[willShareName stringByAppendingPathExtension:@"png"]];
    
    NSURL *URL = [NSURL fileURLWithPath:willPreviewPath];
    if (URL) {
        // Initialize Document Interaction Controller
        UIDocumentInteractionController *documentInteractionController = [UIDocumentInteractionController interactionControllerWithURL:URL];
        documentInteractionController.delegate = self;
        [documentInteractionController presentPreviewAnimated:YES];
    }
}
- (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller
{
    return self;
}

#pragma mark - Ad Delegate
- (void)adViewDidReceiveAd:(GADBannerView *)view
{
    [UIView animateWithDuration:0.2 animations:^{
        CGRect tableRect = self.tblItems.frame;
        CGRect bannerRect = self.viewAd.frame;
        
        tableRect.size.height = self.view.frame.size.height - bannerRect.size.height;
        bannerRect.origin.y = tableRect.size.height;
        
        self.tblItems.frame = tableRect;
        self.viewAd.frame = bannerRect;
    }];
}
- (void)adView:(GADBannerView *)view didFailToReceiveAdWithError:(GADRequestError *)error
{
    NSLog(@"Ad Error:%@",error);
    [UIView animateWithDuration:0.2 animations:^{
        CGRect tableRect = self.tblItems.frame;
        CGRect bannerRect = self.viewAd.frame;
        
        tableRect.size.height = self.view.frame.size.height;
        bannerRect.origin.y = tableRect.size.height;
        
        self.tblItems.frame = tableRect;
        self.viewAd.frame = bannerRect;
    }];
}


@end
